﻿using Domain;
using MediatR;

namespace Application.AbStractions.Behavior
{
    public class TransactionalPipelineBehavior<TRequest, TResponse>(IUnitOfWork unitOfWork): IPipelineBehavior<TRequest, TResponse>where TRequest : ITransactionalCommand<TResponse>
    {
        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            await using var transaction = await unitOfWork.BeginTransactionAsync();

            var response = await next();

            await unitOfWork.SaveChangesAsync(cancellationToken);

            await transaction.CommitAsync(cancellationToken);

            return response;
        }
    }
}
